package cn.wzvtc.ch5_validation.global;//package com.chapter5_1.global;

import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//统一校验异常处理
//@RestControllerAdvice
public class GlobalExceptionHandlerController {

    //异常处理，将处理的异常类型放入其中
    @ExceptionHandler(ConstraintViolationException.class)
    public void handleConstraintViolationException(HttpServletResponse resp, ConstraintViolationException ex) throws IOException {//ex异常类对象
        String msg = ex.getMessage();//得到异常类对象的放回消息
        String[] msgs = msg.split(": ");//把消息分割出来
        resp.setContentType("text/html; charset=utf-8");
        resp.getWriter().println( msgs[msgs.length-1]);
    }

    @ExceptionHandler(BindException.class)
    public void handleBindException(HttpServletResponse resp, BindException ex) throws IOException {
        BindingResult result = ex.getBindingResult();//获取异常消息
        final List<FieldError> fieldErrors = result.getFieldErrors();//读取所有异常
        List<String> errorMsg = new ArrayList<>();
        for (FieldError error : fieldErrors) {
            errorMsg.add(error.getDefaultMessage()); //把所有异常放入errorMsg
        }
        resp.setContentType("text/html; charset=utf-8");
        resp.getWriter().println( String.join(", ", errorMsg));
    }
}
